package com.synjones.handsetS8;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.util.Log;

import com.synjones.hymodule.Bytes2Bmp;
import com.synjones.hymodule.HYModuleControl;
import com.synjones.hymodule.ImageQualityResult;

/**
 * Created by zhaodianbo on 2016-8-22.
 */
public class S8HyFpModule implements FingerprintReaderInterface {
    //声明设备
    HYModuleControl fpModule;
    Context context;
    Handler outHandler;

    static final int FLAG_NEED_CONTINUE=1;
    static final int FLAG_DONT_CONTINUE=0;
    Bitmap fpBmp;
    private volatile int needContinue=FLAG_NEED_CONTINUE;
    private volatile boolean isScaning=false;
    String fingerPhotoPath;

    byte Template[]=new byte[1024];
    byte TemplateUpdate[]=new byte[1024];
    byte feature[]=new byte[248];
    int needUpdate[]=new int[1];

    int sensorType;//1=大指纹头，2=小指纹头


    public S8HyFpModule(Context context, Handler handler){
        this.context=context;
        fpModule=new HYModuleControl();
        outHandler=handler;
        fingerPhotoPath= context.getFileStreamPath("fingerPhoto").getAbsolutePath();//Environment.getExternalStorageDirectory().getPath()+"/fp";
    }
    @Override
    public void powerOn() {
        fpModule.powerOn();
        if(S8PowerControl.COMPATIBLE_WITH_OLD_MACHINE) {
            // TODO: 2016-9-27 为了兼容老机器测试用，正式版本请使用setFingerPower()
            WtWdPowerUtils.setFingerPowerInclude3v3(context);
        }else {
            WtWdPowerUtils.setFingerPower(context);
        }

        try {
            Thread.sleep(500);//使模块上电完成
        } catch (InterruptedException e) {}
    }

    @Override
    public void powerOff() {
        close();
        fpModule.powerOff();
        if(S8PowerControl.COMPATIBLE_WITH_OLD_MACHINE) {
            // TODO: 2016-9-27  为了兼容老机器测试用，正式版本请使用closeFingerPower()
            WtWdPowerUtils.closeFingerPowerInclude3v3(context);
        }else {
            WtWdPowerUtils.closeFingerPower(context);
        }
    }

    @Override
    public int open() {
        int ret=fpModule.openDevice("/dev/ttyMT1");
        sensorType=fpModule.getSensorType();
        if(sensorType!=1 && sensorType!=2)
            ret=-2;
        return ret;
    }

    public int getSensorType(){
        return sensorType;
    }


    @Override
    public int close() {
        return fpModule.closeDevice();
    }

    @Override
    public int cleanFpFeature() {
        feature=new byte[248];
        Template=new byte[1024];
        return 0;
    }

    @Override
    public FpFeature getFpFeature(boolean showFpImage) {
        if(sensorType!=1&&sensorType!=2) return  null;
        isScaning=true;
        int w=sensorType==1?256:208;
        int h=sensorType==1?360:288;
        byte img[]=new byte[w*h];
        needContinue=FLAG_NEED_CONTINUE;
        fpBmp=null;
        while(needContinue==FLAG_NEED_CONTINUE){
            if(fpModule.scanFinger(3000)==0)
                break;
        }
        int ret=-1;
        if(needContinue==FLAG_NEED_CONTINUE){
            sendMsg(MESSAGE_UPDATE_STATUS, "录入结束，可移开手指，正在传输图像……");
            if(showFpImage)
                ret=fpModule.getImageFastFromSensor(sensorType,img);
            else
                ret=0;
           // else
              //  ret=fpModule.getBinImage(img);
        }else{
            isScaning=false;
            return null;
        }
        //Log.e("AATest", "AAModuleEnroll ret="+ret);
        if(ret>=0){
            feature=new byte[248];
            if(showFpImage) {
                fpBmp = Bytes2Bmp.genBitmap(w, h, img);
            }

            sendMsg(MESSAGE_UPDATE_STATUS, "正在获取指纹特征值……");
            //getImageQuality()获取图像的质量，大约耗时1s，调用getFpFeature()前必须先调用此函数
            //如果不需要获取特征值feature，则可去掉此过程
            ImageQualityResult imageQualityResult=fpModule.getImageQuality();

            if(imageQualityResult!=null && imageQualityResult.isOk()) {

                //获取指纹特征值feature
                int retGetFeature = fpModule.getFpFeature(feature);
                if(retGetFeature==1){
                    byte fpFeatureData[] = new byte[248];
                    System.arraycopy(feature, 0, fpFeatureData, 0, 248);
                    sendMsg(MESSAGE_UPDATE_STATUS, "");
                    return new FpFeature(fpBmp,100, fpFeatureData, "");
                }
            }
            sendMsg(MESSAGE_UPDATE_STATUS, "图像质量差，请重新录入");
            isScaning=false;
            return new FpFeature(fpBmp,-1,null,"");
        }


        isScaning=false;
        return null;
    }


    @Override
    public int setFpFeature(int toWhere, byte[] data) {
        try{
            if(data==null)
                return -1;
            //身份证指纹特征值512字节，其他值为自身特征值248字节
            if(data.length==512){
                feature=new byte[512];
                System.arraycopy(data,0, feature, 0, 512);
                return 0;
            }

            if(data.length==248){
                feature=new byte[248];
                System.arraycopy(data,0, feature, 0, 248);
            }else {
                return -1;
            }
            return 0;
        }catch (Exception e){
        }
        return -1;
    }

    @Override
    public FpVerifyResult verifyFp(int sThreshold) {

        if(sensorType!=1&&sensorType!=2) return  null;
        isScaning=true;

        needContinue=FLAG_NEED_CONTINUE;
        while(needContinue==FLAG_NEED_CONTINUE){
            if(fpModule.scanFinger(3000)==0)
                break;
        }

        if (needContinue != FLAG_NEED_CONTINUE) {
            isScaning = false;
            return null;
        }

        if(feature.length==248) {//对比自身采集过的特征值
            int ret = -1;
            int w=sensorType==1?256:208;
            int h=sensorType==1?360:288;
            byte img[]=new byte[w*h];
            sendMsg(MESSAGE_UPDATE_STATUS, "录入结束，可移开手指，正在传输图像……");
            ret = fpModule.getImageFastFromSensor(sensorType, img);
            isScaning = false;
            if (ret >= 0) {
                Template = new byte[1024];
                Bytes2Bmp.save2BMPFile(w, h, img, fingerPhotoPath);
                //可以用多个图像文件合成指纹模板 对比时更加精确
                ret = fpModule.genarateTemplateFromFile(fingerPhotoPath, null, null, 1, 0, Template);
                sendMsg(MESSAGE_UPDATE_STATUS, "");
                if (ret == 1) {//sThreshold可设置为40
                    int retMatch = fpModule.fpMatch(Template, feature, sThreshold, needUpdate, TemplateUpdate);
                    if (retMatch == 1) {
                        return new FpVerifyResult(true, 100, 0);
                    }
                }
            }else {
                sendMsg(MESSAGE_UPDATE_STATUS, "获取图像失败");
                isScaning = false;
                return new FpVerifyResult(false,0,0);
            }
        }else {//对比身份证指纹特征值 //sThreshold可设置为40
            sendMsg(MESSAGE_UPDATE_STATUS, "扫描结束，可移开手指，正在比对……");
            isScaning = false;
            ImageQualityResult imageQualityResult = fpModule.getImageQuality();
            int retMatch = fpModule.fpGABMatch(feature, sThreshold);
            if (retMatch == 1) {
                sendMsg(MESSAGE_UPDATE_STATUS, "");
                return new FpVerifyResult(true, 100, 0);
            } else if (retMatch == 2 && imageQualityResult != null && !imageQualityResult.isOk()) {
                sendMsg(MESSAGE_UPDATE_STATUS, "图像质量差，请重新扫描比对");
                return new FpVerifyResult(false,0,0);
            }
        }
        isScaning = false;
        sendMsg(MESSAGE_UPDATE_STATUS, "对比结束");
        return new FpVerifyResult(false,0,0);
    }

    @Override
    public void cancel() {
        needContinue=FLAG_DONT_CONTINUE;
        while (isScaning);
    }

    @Override
    public int calibration() {
        return -1;
    }


    private void sendMsg(int what,String msg){
        if(outHandler!=null)
            outHandler.obtainMessage(what,msg).sendToTarget();
    }


}
